<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
        }
        
        .login-container {
            background-color: white;
            padding: 2rem;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 400px;
        }
        
        h2 {
            text-align: center;
            color: #333;
            margin-bottom: 1.5rem;
        }
        
        .form-group {
            margin-bottom: 1rem;
        }
        
        label {
            display: block;
            margin-bottom: 0.5rem;
            color: #666;
        }
        
        input {
            width: 100%;
            padding: 0.5rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 1rem;
        }
        
        button {
            width: 100%;
            padding: 0.75rem;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 1rem;
            cursor: pointer;
            margin-top: 1rem;
        }
        
        button:hover {
            background-color: #0056b3;
        }
        
        p {
            text-align: center;
            margin-top: 1rem;
        }
        
        a {
            color: #007bff;
            text-decoration: none;
        }
        
        a:hover {
            text-decoration: underline;
        }
        
        .help-text {
            font-size: 0.8rem;
            color: #666;
            margin-top: 0.25rem;
        }
        
        .error {
            color: #dc3545;
            font-size: 0.9rem;
            margin-top: 0.25rem;
            display: none;
        }
        
        .code-input-group {
            display: flex;
            gap: 10px;
        }
        
        .code-input-group input {
            flex: 1;
        }
        
        .get-code-btn {
            width: 120px;
            background-color: #28a745;
        }
        
        .get-code-btn:hover {
            background-color: #218838;
        }
        
        .get-code-btn:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
    </style>
</head>
<body>
    <div class="login-container">
        <h2>用户注册</h2>
        <form id="register-form">
            <div class="form-group">
                <label for="username">用户名：</label>
                <input type="text" id="username" name="username" required>
                <div class="help-text">用户名长度至少4个字符，只能包含字母、数字和下划线</div>
                <div id="username-error" class="error"></div>
            </div>
            <div class="form-group">
                <label for="password">密码：</label>
                <input type="password" id="password" name="password" required>
                <div class="help-text">密码长度至少8个字符，必须包含字母和数字</div>
                <div id="password-error" class="error"></div>
            </div>
            <div class="form-group">
                <label for="confirm-password">确认密码：</label>
                <input type="password" id="confirm-password" name="confirm-password" required>
                <div id="confirm-password-error" class="error"></div>
            </div>
            <div class="form-group">
                <label for="phone">手机号码：</label>
                <input type="tel" id="phone" name="phone" placeholder="必填" required>
                <div class="help-text">请输入11位中国大陆手机号码</div>
                <div id="phone-error" class="error"></div>
            </div>
            <div class="form-group">
                <label for="verification-code">验证码：</label>
                <div class="code-input-group">
                    <input type="text" id="verification-code" name="verification-code" placeholder="请输入验证码" required>
                    <button type="button" id="get-code-btn" class="get-code-btn">获取验证码</button>
                </div>
                <div class="help-text">请输入收到的6位验证码</div>
                <div id="code-error" class="error"></div>
            </div>
            <button type="submit">注册</button>
        </form>
        <p>已有账号？<a href="{{ url_for('login') }}">立即登录</a></p>
    </div>
    <script>
        // 前端验证函数
        function validateUsername(username) {
            if (!username) {
                return { valid: false, message: '用户名不能为空' };
            }
            if (username.length < 4) {
                return { valid: false, message: '用户名长度不能少于4个字符' };
            }
            if (!/^[a-zA-Z0-9_]+$/.test(username)) {
                return { valid: false, message: '用户名只能包含字母、数字和下划线' };
            }
            return { valid: true, message: '' };
        }
        
        function validatePassword(password) {
            if (!password) {
                return { valid: false, message: '密码不能为空' };
            }
            if (password.length < 8) {
                return { valid: false, message: '密码长度不能少于8个字符' };
            }
            if (!(/[A-Za-z]/.test(password) && /[0-9]/.test(password))) {
                return { valid: false, message: '密码必须包含字母和数字' };
            }
            return { valid: true, message: '' };
        }
        
        function validatePhone(phone) {
            if (!phone) {
                return { valid: false, message: '手机号码不能为空' };
            }
            if (!/^1[3-9]\d{9}$/.test(phone)) {
                return { valid: false, message: '请输入有效的手机号码' };
            }
            return { valid: true, message: '' };
        }

        // 获取验证码倒计时
        let countdown = 60;
        let timer = null;
        const getCodeBtn = document.getElementById('get-code-btn');
        
        function startCountdown() {
            getCodeBtn.disabled = true;
            getCodeBtn.textContent = `${countdown}秒后重新获取`;
            
            timer = setInterval(() => {
                countdown--;
                if (countdown > 0) {
                    getCodeBtn.textContent = `${countdown}秒后重新获取`;
                } else {
                    clearInterval(timer);
                    getCodeBtn.textContent = '获取验证码';
                    getCodeBtn.disabled = false;
                    countdown = 60;
                }
            }, 1000);
        }
        
        // 获取验证码事件
        getCodeBtn.addEventListener('click', async () => {
            const phone = document.getElementById('phone').value.trim();
            
            // 重置手机号错误信息
            const phoneError = document.getElementById('phone-error');
            phoneError.style.display = 'none';
            phoneError.textContent = '';
            
            // 验证手机号格式
            const phoneResult = validatePhone(phone);
            if (!phoneResult.valid) {
                phoneError.textContent = phoneResult.message;
                phoneError.style.display = 'block';
                return;
            }
            
            try {
                const response = await fetch('{{ url_for("send_verification_code") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ phone, type: 'register' })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    alert('验证码已发送，请查收');
                    startCountdown();
                    // 调试模式：显示验证码
                    if (data.debug_code) {
                        console.log('验证码：', data.debug_code);
                        // 可以选择在页面上显示验证码（仅测试环境）
                        document.getElementById('verification-code').value = data.debug_code;
                    }
                } else {
                    phoneError.textContent = data.message || '发送验证码失败';
                    phoneError.style.display = 'block';
                }
            } catch (error) {
                console.error('发送验证码错误:', error);
                phoneError.textContent = '发送验证码时发生错误，请稍后重试';
                phoneError.style.display = 'block';
            }
        });

        // 表单提交事件
        document.getElementById('register-form').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // 获取输入值
            const username = document.getElementById('username').value.trim();
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirm-password').value;
            const phone = document.getElementById('phone').value.trim();
            const code = document.getElementById('verification-code').value.trim();
            
            // 重置所有错误信息
            document.querySelectorAll('.error').forEach(el => {
                el.style.display = 'none';
                el.textContent = '';
            });
            
            // 验证输入
            let hasError = false;
            
            // 验证用户名
            const usernameResult = validateUsername(username);
            if (!usernameResult.valid) {
                const usernameError = document.getElementById('username-error');
                usernameError.textContent = usernameResult.message;
                usernameError.style.display = 'block';
                hasError = true;
            }
            
            // 验证密码
            const passwordResult = validatePassword(password);
            if (!passwordResult.valid) {
                const passwordError = document.getElementById('password-error');
                passwordError.textContent = passwordResult.message;
                passwordError.style.display = 'block';
                hasError = true;
            }
            
            // 验证确认密码
            if (password !== confirmPassword) {
                const confirmPasswordError = document.getElementById('confirm-password-error');
                confirmPasswordError.textContent = '两次输入的密码不一致';
                confirmPasswordError.style.display = 'block';
                hasError = true;
            }
            
            // 验证手机号
            const phoneResult = validatePhone(phone);
            if (!phoneResult.valid) {
                const phoneError = document.getElementById('phone-error');
                phoneError.textContent = phoneResult.message;
                phoneError.style.display = 'block';
                hasError = true;
            }
            
            // 验证验证码
            if (!code) {
                const codeError = document.getElementById('code-error');
                codeError.textContent = '请输入验证码';
                codeError.style.display = 'block';
                hasError = true;
            }
            
            // 如果有错误，阻止提交
            if (hasError) {
                return;
            }
            
            // 准备提交数据
            const data = {
                username: username,
                password: password,
                phone: phone,
                code: code
            };
            
            try {
                // 调试日志
                console.log("提交注册数据:", data);
                
                // 提交到服务器
                const response = await fetch('{{ url_for("register") }}', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                
                const result = await response.json();
                console.log("注册结果:", result);
                
                if (result.success) {
                    // 注册成功，跳转到登录页
                    alert('注册成功！请登录。');
                    window.location.href = '{{ url_for("login") }}';
                } else {
                    // 注册失败，显示错误消息
                    alert(result.message || '注册失败，请稍后重试');
                }
            } catch (error) {
                console.error('Error:', error);
                alert('提交请求时发生错误，请稍后重试');
            }
        });
    </script>
</body>
</html> 